<template>
  <up-overlay :show="showVideo" :opacity="1">
    <video
      @waiting="waiting"
      @timeupdate="timeupdateFn"
      @touchstart="touchStart"
      @touchend="touchEnd"
      autoplay
      class="playVideo"
      ref="videoRef"
      :src="videoUrl"
      :show-fullscreen-btn="false"
      :enable-play-gesture="true"
      controls
    ></video>
    <view class="handleClose">
      <image @tap="handleClose" src="@/static/image/38.png" mode="widthFix" />
    </view>
  </up-overlay>
</template>

<script setup lang="ts">
import { ref } from "vue";

let showVideo = ref<boolean>(false);
let isLoading = ref<boolean>(false);
let videoUrl = ref<string>();
let startY = ref<number>();
const playVideoFn = (item: any) => {
  videoUrl.value = item.Content.Url;
  showVideo.value = true;

  // H5 平台下进入全屏模式
  // #ifdef H5
  const videoRef = ref<HTMLVideoElement | null>(null);
  const video = videoRef.value;
  if (video?.requestFullscreen) {
    video.requestFullscreen();
  } else if ((video as any)?.mozRequestFullScreen) {
    (video as any)?.mozRequestFullScreen();
  } else if ((video as any)?.webkitRequestFullscreen) {
    (video as any)?.webkitRequestFullscreen();
  } else if ((video as any)?.msRequestFullscreen) {
    (video as any)?.msRequestFullscreen();
  }
  // #endif
};
const waiting = () => {
  if (!isLoading.value) {
    isLoading.value = true;
    uni.showLoading();
  }
};
const timeupdateFn = () => {
  if (isLoading.value) {
    isLoading.value = false;
    uni.hideLoading();
  }
};

const touchStart = (event: any) => {
  startY.value = event.touches[0].clientY;
};
const touchEnd = (event: any) => {
  const endY = event.changedTouches[0].clientY;
  if (startY.value) {
    const distanceY = endY - startY.value;
    if (distanceY > 50) {
      handleClose();
    }
  }
};
const handleClose = () => {
  uni.hideLoading();
  /*#ifdef H5*/
  const videoRef = ref<HTMLVideoElement | null>(null);
  const video = videoRef.value;
  if (video) {
    video?.pause();
    video.currentTime = 0;
  }
  /*#endif*/
  showVideo.value = false;
};

defineExpose({
  playVideoFn,
});
</script>

<style scoped lang="scss">
@import "../../../static/scss/chat.scss";
</style>
